#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "header.h"



int appartient_permutation(int c,int** tabl,int nb_permutations)
{

    int boolean=0;
    int i=0;
    int res=-1;


    while ((boolean==0) && (i<nb_permutations*2))
    {

        if (tabl[i][0]==c)
        {
            boolean=1;
            res=tabl[i][1];
        }
        i++;
    }

    return res;
}



void decaler_rotor(Rotor_intern* r)
{
    int i=0;
    int tmp = r->sorties[0];
    int temp;


    for (i=0;i<25;i++)
    {
        temp = (r->sorties[i+1]-1);
        if (temp<0)
            temp=25;
        r->sorties[i]=temp;
    }
    if (tmp==0)
        tmp=26;
    r->sorties[25]=(tmp-1);
}



void mouvement_rotors(Rotor_intern* r1, Rotor_intern* r2, Rotor_intern* r3, int* pos_r1, int* pos_r2, int* pos_r3)
{
    *(pos_r1)=(*(pos_r1)+1)%26;
    decaler_rotor(r1);

    if (*(pos_r1)==r1->encoche)
    {
        *(pos_r2)=(*(pos_r2)+1)%26;
        decaler_rotor(r2);
    }

    if (*(pos_r2)==r2->encoche)
    {
        *(pos_r3)=(*(pos_r3)+1)%26;
        decaler_rotor(r3);
        *(pos_r2)=(*(pos_r2)+1)%26;
        decaler_rotor(r2);
    }
}







int traitement(Rotor_intern* r1, Rotor_intern* r2, Rotor_intern* r3, Reflecteur* refl, Plugboard* plugb, int* pos_r1, int* pos_r2, int* pos_r3, int c, int nb_permutations)
{

    int temp;
    int temp2;
    int i=0,boolean=0;


    mouvement_rotors(r1,r2,r3,pos_r1,pos_r2,pos_r3);

    temp=appartient_permutation(c,plugb->connexions,nb_permutations);

    if (temp<0)
        temp=c;

    temp2 = r1->sorties[temp]; /* passage au rotor 1 */

    temp = r2->sorties[temp2];  /* passage au rotor 2 */

    temp2 = r3->sorties[temp];  /* passage au rotor 3 */

    temp = refl->sorties[temp2];





    i=0;
    boolean=0;


    while ((i<26) && (boolean!=-1))
    {
        if (r3->sorties[i]==temp)
        {
            boolean=-1;
            temp2 = i;
        }

        else
            i++;
    }





    i=0;
    boolean=0;


    while ((i<26) && (boolean!=-1))
    {
        if (r2->sorties[i]==temp2)
        {
            boolean=-1;
            temp = i;
        }

        else
            i++;
    }





    i=0;
    boolean=0;

    while ((i<26) && (boolean!=-1))
    {
        if (r1->sorties[i]==temp)
        {
            boolean=-1;
            temp2 = i;
        }

        else
            i++;
    }


    temp = appartient_permutation(temp2,plugb->connexions,nb_permutations);

    if (temp!=-1)
        return temp;
    else
        return temp2;
}







char int_to_char(int i, int flag)
{
    if (flag)
        return (char) i+97;
    else return (char) i+65;
}

